package com.gk.javaservice.controller;

import com.gk.javaservice.common.ServerResponse;
import com.gk.javaservice.po.AdminUsers;
import com.gk.javaservice.service.AdminUsersService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.UUID;

@Controller
@RequestMapping("/login")
public class loginController {

    private Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private AdminUsersService adminUsersService;

    @CrossOrigin
    @ResponseBody
    @GetMapping("/login")
    public ServerResponse<?> login(HttpServletRequest request, HttpSession session) {
        log.info("in to login");
//        int isLogin=Integer.parseInt(request.getParameter("isLogin"));
        AdminUsers u = new AdminUsers();
        u.setUsername(request.getParameter("name"));
        u = adminUsersService.autoLogin(u);
        if (u == null) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        log.info("User: " + u);
        String token2 = UUID.randomUUID().toString(); // 生成唯一的token
        if (u.getIs_login() == 1) {

        } else {
            UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("name"), request.getParameter("pwd"));
            //UsernamePasswordToken token=new UsernamePasswordToken("root", MD5Encryption.encryption("123456",1,null,null));


            //UsernamePasswordToken token=new UsernamePasswordToken("root", "123456");

            try {
                SecurityUtils.getSubject().login(token);


//                log.info("token2:" + token2);
                u = (AdminUsers) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
                u.setRemember_token(token2);

                session.setAttribute(token2, SecurityUtils.getSubject().getSession().getAttribute("loginUser"));

            } catch (AuthenticationException e) {
                log.info("Login failed: " + e);
                SecurityUtils.getSubject().logout();
                try {
                    session.removeAttribute("loginUser");
                } catch (Exception ex) {

                }
                return ServerResponse.createByErrorMessage("登陆失败！");
            }


            u = (AdminUsers) session.getAttribute(token2);
        }

        u.setPassword(request.getParameter("pwd"));
        adminUsersService.update(u);

//        log.info("user:" + u);
        return ServerResponse.createBySuccess(u);
    }

    @CrossOrigin
    @ResponseBody
    @GetMapping("/loginOut")
    public ServerResponse<?> loginOut(HttpServletRequest request, HttpSession session) {
        log.info("in to loginOut");
        SecurityUtils.getSubject().logout();
        try {
            session.removeAttribute(request.getParameter("token"));
        } catch (Exception e) {

        }

        return ServerResponse.createBySuccess(1);
    }

    @CrossOrigin
    @ResponseBody
    @GetMapping("/hasLoginMsg")
    public ServerResponse<?> hasLoginMsg(HttpServletRequest request, HttpSession session) {
        log.info("in to hasLoginMsg");
//        AdminUsers au= DataMapUtil.getObject(request.getParameter("token"), AdminUsers.class);
        AdminUsers au = (AdminUsers) session.getAttribute(request.getParameter("token"));
        return ServerResponse.createBySuccess(au);
    }

    @CrossOrigin
    @ResponseBody
    @GetMapping("/sessionT")
    public ServerResponse<?> sessionT(HttpSession session) {
        log.info("in to sessionT");
        try {
            Enumeration enumeration = session.getAttributeNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement().toString();
                log.info("WebUtil chearCache key:{}" + key);
//                session.removeAttribute(key);
//                log.info("WebUtil removeAttribute key:{}"+ key);
            }
        } catch (Exception e) {
            log.error("chearCache error {}" + e.getMessage());
            e.printStackTrace();
        }


        return ServerResponse.createBySuccess();
    }

}
